package com.lry.crawlers.fiction.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lry.crawlers.fiction.entity.FictionChapter;
import com.lry.crawlers.fiction.mapper.FictionChapterMapper;
import com.lry.crawlers.fiction.service.FictionChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FictionChapterServiceImpl implements FictionChapterService {

    @Autowired
    FictionChapterMapper fictionChapterMapper;


    @Override
    public int setFictionChapter(FictionChapter fictionChapter) {
        int insert = fictionChapterMapper.insert(fictionChapter);
        return insert;
    }

    @Override
    public int setFictionChapters(List<FictionChapter> fictionChapters) {
        int i = fictionChapterMapper.insertBatchSomeColumn(fictionChapters);
        return i;
    }

    @Override
    public String getChapterPath(String chapterId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("chapter_id",chapterId);
        FictionChapter fictionChapter = fictionChapterMapper.selectOne(wrapper);
        if(fictionChapter!=null){
            return fictionChapter.getChapterPath();
        }
        return null;
    }

    @Override
    public List<FictionChapter> selectByFictionId(String fictionId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("fiction_id",fictionId);
        List<FictionChapter> list = fictionChapterMapper.selectList(wrapper);
        if(list!=null){
            return list;
        }
        return null;
    }

    @Override
    public List<Integer> removeDuplicates(List<String> titles, List<FictionChapter> FictionChapters) {
        List<Integer> duplicates = new ArrayList<>();
        List<String> titlesy = new ArrayList<>();
        for (FictionChapter fictionChapter : FictionChapters) {
            titlesy.add(fictionChapter.getTitle().trim());
        }
        for(int i = 0;i<titles.size();i++){
            boolean contains = titlesy.contains(titles.get(i));
            if(contains){
                duplicates.add(i);
            }
        }
        return  duplicates;
    }

    @Override
    public int setFictionChapterUp(FictionChapter fictionChapter) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("chapter_id",fictionChapter.getChapterId());
        return fictionChapterMapper.update(fictionChapter,wrapper);
    }
}

